<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 组织架构 -->
      <el-card class="tree-card">
        <TreeTools :tree-node="company" :is-root="true" @addDepts="addDepts" />
        <!-- 树状图，默认展开 -->
        <el-tree :data="departs" :default-expand-all="true" :props="defaultProps">
          <!-- 插槽内容会循环节点数次 作用域插槽slot-scope接收传递给插槽的数据，data是每个节点的数据对象-->
          <TreeTools slot-scope="{data}" :tree-node="data" @delDepts="getDepartments" @addDepts="addDepts" @editDepts="editDepts" />
        </el-tree>
      </el-card>
    </div>
    <!-- 添加弹窗 -->
    <AddDept v-if="showDialog" ref="addDept" :show-dialog.sync="showDialog" :tree-node="node" @addDepts="getDepartments" />
  </div>
</template>

<script>
import TreeTools from './components/tree-tools.vue'
import AddDept from './components/add-dept.vue'
import { getDepartments } from '@/api/departments'
import { tranListToTreeData } from '@/utils/index'
export default {
  components: {
    TreeTools,
    AddDept
  },
  data() {
    return {
      company: { name: '', manager: '负责人', id: '' }, // 头部栏
      departs: [],
      defaultProps: {
        label: 'name'// 属性改名
      },
      showDialog: false, // 添加弹窗是否显示
      node: null,
      form: {}
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    // 获取并渲染数据
    async getDepartments() {
      const result = await getDepartments()
      this.company.name = result.companyName
      this.departs = tranListToTreeData(result.depts, '')// 转换为树形结构
    },
    // 添加子部门
    addDepts(node) {
      this.node = node
      this.showDialog = true
    },
    // 编辑详情
    editDepts(node) {
      this.node = node
      setTimeout(() => { this.$refs.addDept.getDepartDetail(node.id) }, 0) // 父组件调用子组件的方法，v-if后获取$refs需要异步计时器
      this.showDialog = true
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>

